<?php
class TourGiftService {
    private static $instance;

    public static function get() {
        if (!self::$instance) {
            self::$instance = new TourGiftService();
        }
        return self::$instance;
    }

    protected function __construct() {

    }

    /**
     * 获取玩家数据
     * @param $userId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function giftInfo($userId,$reqTime) {
        //获取巡回礼包配置
        $tourGiftConfs = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_TOUR, null, true,false);
        if (!$tourGiftConfs || empty($tourGiftConfs)){
            throw new SzException(90082);//配置不存在
        }

        $results = array();
        /**
         * @var $userGiftPackList GiftPackVoList
         */
        $userGiftPackList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_GIFT_PACK);
        /**
         * 获取玩家商品数据
         * @var ModuleItemVoList $flowerList
         */
        $flowerList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);
        $platform = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_USER_PLATFORM);
        if ($platform == 'hago'){
            $platformPre = 'hago';
        }
        elseif ($platform == 'H5WeChat' || $platform == 'dev'){
            $platformPre = 'weixin';
        }
        else{
            $platformPre = 'wanba';
        }

        foreach ($tourGiftConfs as $key=>$tourGiftConf){
            //获取时间
            $tourTime = strtotime($tourGiftConf[$platformPre.'StartTime']);
            if ($reqTime < $tourTime){
                break;
            }

            /**
             * @var TourGiftVoList $tourGiftList
             * @var TourGiftVo $tourGiftInfo
             */
            //获取玩家巡回礼包数据
            $tourGiftList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_TOUR_GIFT);
            $tourGiftInfo = $tourGiftList->getElement($tourGiftConf['id'],false);
            //获取老玩家已经购买的礼包数据
            $buyArr = array();
            /**
             * @var $userGiftPack GiftPackVo
             */
            foreach ($tourGiftConf['giftId'] as $key1=>$giftID){
                $userGiftPack = $userGiftPackList->getElement($giftID, false);
                if ($userGiftPack && $userGiftPack->getStatus() == 1){
                    $buyArr[] = $giftID;
                }

                //老玩家拥有花卡
                $item = $flowerList->getElementsByItemDefId($tourGiftConf['flowerId'][$key1]);
                if ($item) {
                    if (!in_array($giftID,$buyArr)){
                        $buyArr[] = $giftID;
                    }
                }
            }

            if (!$tourGiftInfo){//新建巡回礼包数据
                $buySituation = '';
                $rewardSituation = '';
                if (!empty($buyArr)){
                    if (count($buyArr) == 1){
                        $buySituation = (string)$buyArr[0];
                        $rewardSituation = '0,0';
                    }
                    elseif (count($buyArr) == 0){
                        $rewardSituation = '0,0';
                    }
                    else{
                        $buySituation = implode(',',$buyArr);
                        if (count($buyArr) == 2){
                            $rewardSituation = '1,0';
                        }
                        if (count($buyArr) == 3){
                            $rewardSituation = '1,1';
                        }
                    }
                }

                $tourGiftInfo = new TourGiftVo(
                    $userId,
                    $tourGiftConf['id'],
                    json_encode($buySituation),
                    json_encode($rewardSituation),
                    $reqTime,
                    0,
                    true
                );
            }
            else{
                $hasStr = json_decode($tourGiftInfo->getBuySituation());
                $hasInfo = explode(',',json_decode($tourGiftInfo->getBuySituation()));
                //验证已有礼包是否真实存在
                if ($hasStr != '' && count($hasInfo)){
                    foreach ($hasInfo as $gid=>$good){
                        if (!in_array($good,$buyArr)){
                            unset($hasInfo[$gid]);
                        }
                    }
                    $hasStr = implode(',',$hasInfo);
                }
                //重新入库
                foreach ($buyArr as $key=>$buyId){
                    if (in_array($buyId,$hasInfo)){
                        unset($buyArr[$key]);
                    }
                    else{
                        if ($hasStr == ''){
                            $hasStr = $buyId;
                        }
                        else{
                            $hasStr = $hasStr.','.$buyId;
                        }
                    }
                }

                //获取玩家已领取奖励部分
                $oneStep = true;
                $secStep = true;
                $oldStr = json_decode($tourGiftInfo->getRewardSituation());
                if ($oldStr != ''){
                    $oldSituation = explode(',',$oldStr);
                    if ($oldSituation[0] == 2){
                        $oneStep = false;
                    }
                    if ($oldSituation[1] == 2){
                        $secStep = false;
                    }
                }

                $num = count(explode(',',$hasStr));
                if ($oneStep && $secStep){
                    if ($num == 0 || $num == 1){
                        $tourGiftInfo->setRewardSituation('0,0');
                    }
                    elseif ($num == 2){
                        $tourGiftInfo->setRewardSituation('1,0');
                    }
                    else{
                        $tourGiftInfo->setRewardSituation('1,1');
                    }
                }

                if (!$oneStep && $secStep){
                    if ($num == 3){
                        $tourGiftInfo->setRewardSituation('2,1');
                    }
                }

                if ($oneStep && !$secStep){
                    if ($num == 3){
                        $tourGiftInfo->setRewardSituation('1,2');
                    }
                }

                $tourGiftInfo->setBuySituation($hasStr);
            }

            if ($tourGiftInfo->isInsert() && !SzUtility::checkArrayKey($tourGiftConf['id'], $tourGiftList->getList())) {
                $tourGiftList->addElement($tourGiftInfo);
                $tourGiftList->setElement($tourGiftConf['id'],$tourGiftInfo);
            }
            else{
                $tourGiftList->updateElement($tourGiftConf['id'], $tourGiftInfo);
            }

            SzPersister::get()->setVoList($tourGiftList);
            $results[$tourGiftConf['id']] = $tourGiftInfo->toArray();
        }

        return $results;
    }

    /**
     * 领取奖励
     * @param $userId
     * @param $id
     * @param $step
     * @param $reqTime
     * @return bool
     * @throws SzException
     */
    public function getReward($userId,$id,$step,$reqTime) {
        //获取巡回礼包配置
        $tourGiftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_TOUR, $id, true,false);
        if (!$tourGiftConf || empty($tourGiftConf)){
            throw new SzException(90082);//配置不存在
        }
        $platform = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_USER_PLATFORM);
        if ($platform == 'hago'){
            $platformPre = 'hago';
        }
        elseif ($platform == 'H5WeChat'){
            $platformPre = 'weixin';
        }
        else{
            $platformPre = 'wanba';
        }
        $tourTime = strtotime($tourGiftConf[$platformPre.'StartTime']);
        if ($reqTime < $tourTime){
            throw new SzException(90001);//礼包没有开始出售
        }

        /**
         * @var TourGiftVoList $tourGiftList
         * @var TourGiftVo $tourGiftInfo
         */
        //获取玩家巡回礼包数据
        $tourGiftList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_TOUR_GIFT);
        $tourGiftInfo = $tourGiftList->getElement($id,false);
        if (!$tourGiftInfo){
            throw new SzException(90083);//请先购买相关礼包
        }

        $buyStr = json_decode($tourGiftInfo->getBuySituation());

        $buySituation = array();
        if (strpos($buyStr,',') == false){
            $buySituation[] = $buyStr;
        }
        else{
            $buySituation = explode(',',$buyStr);
        }

        $getStep = count($buySituation);
        if ($getStep < 2){
            throw new SzException(90084);//无权兑换额外奖励
        }


        $situationStr = json_decode($tourGiftInfo->getRewardSituation());
        $getSituationArr = explode(',',$situationStr);
        $rewardArr = $tourGiftConf['rewardId'];
        $reward = 0;
        $num = 0;

        if ($step == 1){
            if ($getStep == 2 || $getStep == 3){
                if ($getSituationArr[0] == 2){
                    throw new SzException(90085);//已经领取奖励
                }
                else{
                    $getSituationArr[0] = 2;
                }

                //给玩家奖励
                list($reward, $num) = (reset($rewardArr) ? each($rewardArr) : each($rewardArr));
                GameService::get()->handleEntity($userId,$reward, $num, true);
                $tourGiftInfo->setRewardSituation(implode(',',$getSituationArr));
            }
        }

        if ($step == 2){
            if ($getStep == 3){
                if ($getSituationArr[1] == 2){
                    throw new SzException(90085);//已经领取奖励
                }
                else{
                    $getSituationArr[1] = 2;
                }

                //给玩家奖励
                $isGet = false;
                list($reward, $num) = (end($rewardArr) ? each($rewardArr) : each($rewardArr));
                $getFlowerId = substr($reward,4);

                /**
                 * @var ModuleItemVoList $itemList
                 */
                $itemList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);
                $item = $itemList->getElementsByItemDefId($getFlowerId);
                if ($item) {
                    list($reward, $num) = (reset($tourGiftConf['replaceReward']) ? each($tourGiftConf['replaceReward']) : each($tourGiftConf['replaceReward']));
                }

                GameService::get()->handleEntity($userId,$reward, $num, true);
                $tourGiftInfo->setRewardSituation(implode(',',$getSituationArr));
            }
        }

        $tourGiftList->updateElement($id,$tourGiftInfo);
        SzPersister::get()->setVoList($tourGiftList);

        return true;
    }

}
